<template>
  <div class="container">
    <!-- 左侧主要部分 -->
    <el-form ref="form" :model="form" class="main">
      <h2>发表新攻略</h2>
      <p class="shuoming">分享你的个人游记，让更多人看到哦！</p>
      <el-form-item>
        <el-input
          placeholder="请输入标题"
          class="biao"
          v-model="form.title"
        ></el-input>
      </el-form-item>

      <!-- 富文本框 -->
      <client-only>
        <VueEditor
          v-model="form.content"
          class="wenzi"
          :editorToolbar="customToolbar"
        />
      </client-only>

      <!-- 选择城市模块 -->
      <!-- fetch-suggestions 返回输入建议的方法 -->
      <!-- select 点击选中建议项时触发 -->
      <el-row class="demo-autocomplete">
        <el-col>
          <div class="sub-title">选择城市</div>
          <el-autocomplete
            class="inline-input"
            v-model="cityName"
            :fetch-suggestions="querySearch"
            placeholder="请搜索游玩城市"
            :trigger-on-focus="false"
            :highlight-first-item="true"
            @select="handleSelect"
          ></el-autocomplete>
        </el-col>
      </el-row>

      <div class="publish">
        <el-button type="primary" class="fabu" @click="publishWay()"
          >发布</el-button
        >
        <span>或者</span>
        <a href="javascript:;" @click="draft()">保存到草稿</a>
      </div>
    </el-form>

    <!-- 右侧草稿箱部分 -->
    <div class="aside">
      <div class="caogao">
        草稿箱 ({{ $store.state.draftsstore.draftsList.length }})
      </div>
      <div
        class="drafts"
        v-for="(item, index) in $store.state.draftsstore.draftsList"
        :key="index"
      >
        <div class="biaoti" @click="edit(item, index)">{{ item.title }}</div>
        <div class="riqi">
          <span>{{ item.date }}</span>
          <i class="el-icon-delete" @click="del(index)"></i>

          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <i class="el-icon-edit" @click="edit(item, index)"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import { VueEditor } from "vue2-editor";
export default {
  data() {
    return {
      // content: "",
      customToolbar: [
        ["bold", "italic", "underline", "strike"],
        [{ header: "1" }, { header: "2" }],
        ["image"],
      ],
      // baseURL: axios.defaults.baseURL, // 基准路径

      config: {
        uploadImage: {
          url: "http://localhost:3000/upload", // 文章上传的服务器端的处理路径
          name: "file", // 后台所需要的参数名称
          // headers: this.getToken(),
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            // 文件上传成功之后的回调
            console.log(res);
            insert("http://localhost:3000/upload" + res.data.data.url);
          },
        },
      },
      cityName: "", //显示的城市名

      form: {
        title: "",
        content: "",
        city: "",
      },
    };
  },
  methods: {
    // 发布
    publishWay() {
      console.log(111);
      // console.log(this.form);
      if (this.form.title.trim().length == 0) {
        this.$message.warning("请输入标题");
        return;
      }
      if (this.form.content.trim().replace("<p><br></p>", "").length == 0) {
        this.$message.warning("请输入内容");
        return;
      }
      if (this.form.city.length == 0) {
        this.$message.warning("请输入城市");
        return;
      }

      if (this.$store.state.userstore.userInfo.token)
        this.$axios({
          url: "/posts",
          headers: {
            // 请求头传递token  前加 Bearer
            Authorization:
              "Bearer " + this.$store.state.userstore.userInfo.token,
          },
          method: "POST",
          data: this.form,
        }).then((res) => {
          console.log(res.data);
          if (res.data.message == "新增成功") {
            this.$message.success("发布成功");
            //发布成功则清空表单里的内容
            this.form.title = "";
            this.form.content = "";
            this.cityName = "";
          }
        });
    },

    // 保存为草稿
    draft() {
      console.log(222);
      if (this.form.title.trim().length == 0) {
        this.$message.warning("标题不能为空");
        return;
      }
      this.$store.commit("draftsstore/addDrafts", {
        title: this.form.title,
        city: this.form.city,
        cityName: this.cityName,
        content: this.form.content,
        date: this.getDate(),
      });
      this.$message("保存成功");
      //保存草稿成功则清空表单里的内容
      this.form.title = "";
      this.form.content = "";
      this.cityName = "";
    },

    // 机票城市请求封装
    getCities(value) {
      return this.$axios({
        url: "/airs/city",
        params: { name: value },
      }).then((res) => {
        console.log(res);
        // **必须有value才可以显示出来**  数据需改造
        // filter:过滤掉没有city.sort的元素
        // map：添加value属性
        let cities = res.data.data
          .filter((city) => {
            return city.sort;
          })
          .map((city) => {
            return {
              ...city,
              value: city.name.replace("市", ""),
            };
          });
        console.log(cities);
        return cities.length == 0 ? [{ value: "没有搜索的城市" }] : cities;
      });
    },

    //城市输入框获得焦点时触发
    // value:当前选中的值
    // callback：回调函数，接收要展示的列表
    //   返回输入建议的方法
    querySearch(value, callback) {
      // let value = this.getCities(value);
      console.log(this.getCities(value)); //获取到的promise对象通过.then(res=>{}) 获取结果
      this.getCities(value).then((res) => {
        // 搜索得出建议选项的时候,默认将列表的第一项 code 数据放入 form
        // 默认给一个值, 如果用户自己选了, 再去覆盖
        // 默认将第一项的代码放入 form 表单当中
        // 不用担心用户之后的操作,
        // 如果用户不选择, 默认就有 code
        // 如果用户选择一个城市,
        // 会后续触发 select 事件
        // 用户选择的数据会覆盖掉默认数据
        this.form.city = res[0].name;
        callback(res);
      });
      // callback(this.getCities(value));
    },
    // 点击选中建议项时触发
    // 出发城市下拉选择时触发
    handleSelect(item) {
      console.log(item);
      this.form.city = item.name;
    },

    // 编辑草稿
    edit(item, index) {
      this.form.title = item.title;
      this.form.city = item.city;
      this.form.content = item.content;
      this.cityName = item.cityName;
    },
    // 删除草稿
    del(index) {
      this.$confirm("是否永久删除该草稿?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((res) => {
          if (res) {
            this.$store.commit("draftsstore/del", index);
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((res) => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 获取日期
    getDate() {
      let myDate = new Date();
      const date = {
        year: myDate.getFullYear(),
        month: myDate.getMonth() + 1,
        day: myDate.getDate(),
      };
      return date.year + "-" + date.month + "-" + date.day;
    },
  },
};
</script>

<style lang="less" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.container {
  overflow: hidden;
  width: 1000px;
  margin: 0 auto;
  margin-top: 25px;
  // border: 1px solid red;
  // background-color: pink;
}

.main {
  width: 750px;
  float: left;
}
.main h2 {
  font-size: 22px;
  margin-bottom: 10px;
  font-weight: 400;
}
.main .shuoming {
  font-size: 12px;
  color: #999999;
  margin-bottom: 10px;
}
.main .biao {
  margin-bottom: 25px;
}
.main .wenzi {
  height: 400px;
  margin-bottom: 80px;
}
.demo-autocomplete {
  margin-bottom: 20px;
  overflow: hidden;
}
.sub-title {
  float: left;
  margin-top: 8px;
  font-size: 14px;
  color: #999999;
}
.inline-input {
  margin-left: 15px;
  float: left;
}
.main .publish {
  margin-bottom: 20px;
}
.main .publish .fabu {
  width: 56px;
  height: 32px;
  font-size: 12px;
}
.main .publish span {
  margin-left: 10px;
  font-size: 14px;
}
.main .publish a {
  font-size: 14px;
  color: orange;
}
.main .publish a:hover {
  text-decoration: underline;
}
.aside {
  float: right;
  // margin-left: 25px;
  width: 225px;
  padding: 10px;
  border: 1px solid #cccccc;
}
.aside .biaoti:hover {
  text-decoration: underline;
  color: orange;
}
.aside .caogao {
  color: #666669;
  height: 21.6px;
  margin-bottom: 10px;
}
.aside .riqi span {
  font-size: 12px;
  color: #666669;
}
.aside .riqi i {
  float: right;
  margin-left: 5px;
}
.aside .riqi i:hover {
  color: orange;
  cursor: pointer;
}
</style>

